﻿
using CmdPrep.Algorithms;
using CmdPrep.Backends;
using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace CmdPrep.Frontends
{
    public partial class SdlControl : UserControl
    {
        #region Private data
        
        private DataTable   sdlFilesDataTable_;
        private DataView    sdlInputDataView_;

        #endregion
        
        #region Public events
        
        public delegate void StatusChangedEventHandler(string statusText);
        public event StatusChangedEventHandler statusChanged;

        #endregion
        
        #region Private methods
        
        private void updateUserInterface()
        {
            updateUserInterface(0);
        }
        
        private void updateUserInterface(int additionalCheckCount)
        {
            btnClearSdl.Enabled = (sdlCheckedListBox.Items.Count) > 0;
            btnSaveSdl.Enabled = (sdlCheckedListBox.Items.Count) > 0;
            btnCreateExcel.Enabled = (sdlCheckedListBox.CheckedItems.Count +  additionalCheckCount) > 0;
        }
        
        private void updateSdlCheckedListBox() {
            for (int i =0 ; i < sdlCheckedListBox.Items.Count ; i++ )
                    sdlCheckedListBox.SetItemChecked(i, true) ;
    
        }
        
        #endregion
        
        #region Public foundation
        
        public SdlControl()
        {
            InitializeComponent();
            
            
            sdlFilesDataTable_ = new DataTable();
            sdlFilesDataTable_.Columns.Add(new DataColumn("inputFileName", Type.GetType("System.String")));
            sdlFilesDataTable_.Columns.Add(new DataColumn("inputFullName", Type.GetType("System.String")));
            
            sdlInputDataView_ = new DataView(sdlFilesDataTable_);
            sdlInputDataView_.RowFilter = "";
            
            sdlCheckedListBox.DataSource = sdlInputDataView_;
            sdlCheckedListBox.ValueMember = "inputFullName";
            sdlCheckedListBox.DisplayMember = "inputFileName";
          
            updateUserInterface() ;
        }
        
        #endregion
        
        #region Public methods
        
        public void addInputSdlFileIfExclusive(DataRow sdlInputDataRow)
        {
            if (sdlInputDataRow == null)
                return;
            
            string sdlInputFullName = sdlInputDataRow["fullName"] as string;
            if (sdlInputFullName == null)
                return;
            
            addInputSdlFileIfExclusive(sdlInputFullName);
        }

        public void addInputSdlFileIfExclusive(string sdlInputFullName)
        {
            FileInfo sdlInputFileInfo = new FileInfo(sdlInputFullName);
            addInputSdlFileIfExclusive(sdlInputFileInfo);
        }

        public void addInputSdlFileIfExclusive(FileInfo sdlInputFileInfo)
        {
            bool isExclusive = true;
            foreach (DataRow dataRow in sdlFilesDataTable_.Rows)
                isExclusive &= ! dataRow["inputFileName"].Equals(sdlInputFileInfo.Name);
            
            if (! isExclusive)
                return;
            
            DataRow newRow = sdlFilesDataTable_.NewRow();
            newRow["inputFileName"] = sdlInputFileInfo.Name;
            newRow["inputFullName"] = sdlInputFileInfo.FullName;
            sdlFilesDataTable_.Rows.Add(newRow);
            
            statusChanged("Input file added.");
            updateUserInterface() ;
        }

        #endregion
        
        #region Private event handlers
        
        private void btn_SDL_Open_Files_Click(object sender, EventArgs e) 
        {
            dlgOpenFileSdl.Filter = "SDL Text Files|*.SDL";
            dlgOpenFileSdl.ShowDialog();
        }
        
        private void Open_SDL_Files_FileOk(object sender, CancelEventArgs e) 
        {
            foreach (string detail in dlgOpenFileSdl.FileNames)
                sdlCheckedListBox.Items.Add(detail, true);

            updateUserInterface();
            dlgOpenFileSdl.Reset();
        }
        
        private void Save_SDL_File_FileOk(object sender, CancelEventArgs e) 
        {
            string new_filenamepath = dlgSaveFileSdl.FileName;
            Replacement editing = new Replacement();
            
            string tempFile = @"D:\Uneaque_alter_ego_temp_SDL_List.txt";            
            StreamWriter writer = new StreamWriter(tempFile, false);
            
            foreach (string filenamepath in sdlCheckedListBox.CheckedItems) 
            {
                string line = null;
                //FileInfo reportFile = new FileInfo(filenamepath);
                // create a reader for the file
                // create a writer for the fixed file
                int fromLine = editing.SDLstart(filenamepath);
                int toLine = editing.SDLend(filenamepath);
                if (toLine <1 ) {
                    MessageBox.Show("Finner IKKJE", "</SDL>");
                //    this.Close();
                }
                
                StreamReader reader = new StreamReader(filenamepath);
                int x = 0;
                int pos2 = 0; // pos(ition) to occurence of "RACK"
                while ((line = reader.ReadLine()) != null) 
                {
                    if (x >= fromLine && x <= toLine -1) 
                    {
                        line = editing.remove_left(line, ";", " ");
                        line = editing.remove_right(line, ";", " ");
                        line = editing.remove_end(line, " ");
                        line = editing.replace(line, ";=", ";");
                        if (chbDetectRack.Checked == true) {
                            int pos = editing.FindPos(line, ";", 2);
                            if (pos >0) {
                                pos2 = line.IndexOf("RACK", pos);
                            }
                            if (pos2 >0) {
                                string text = line.Substring(pos2, 6);
                                text = text.Trim();
                                if (text.Length == 5) {
                                    text = text.Substring(0, 4) + "0" + text.Substring(4, 1);
                                }
                                line = editing.add_end(line, ";" + text);
                                pos2 = 0;
                            }
                        }
                        writer.WriteLine(line);
                    }
                    x++;
                  }
                reader.Close();
            }
            writer.Close();

            excel_addin excel = new excel_addin();
            // excel.Rack_Col = chb_detect_rack.Checked;
            //excel.keep_open = chb_Keep_Open.Checked;           
            excel.Rack_Col = true;
            excel.keep_open = true;
            excel.Open_TextFile(tempFile,new_filenamepath);

            File.Delete(tempFile);
            int filenamestart = new_filenamepath.LastIndexOf(@"\") + 1;
            string new_filename = new_filenamepath.Substring(filenamestart);
//            toolStripStatusLabel.ToolTipText = "Generated FileName";
//            toolStripStatusLabel.Text = new_filenamepath;
            MessageBox.Show("File Sucsessfully Created! \n"+new_filenamepath);
        }//private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
///
/// SDL buttoncode starts Here...
///        
        private void btn_generate_Click(object sender, EventArgs e) {
            dlgSaveFileSdl.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            dlgSaveFileSdl.ShowDialog();
        }
        
        private void btn_SDL_clear_Click(object sender, EventArgs e) {
//            toolStripStatusLabel.Text = "";
//            toolTip.RemoveAll();
            sdlFilesDataTable_.Clear();
            updateUserInterface();
        }
        
        private void btn_load_SDLsList_Click(object sender, EventArgs e) {
            string SDLsList;
            string line = null;
        
            SDLsList = @"D:\SDL_File_List.TXT";
            StreamReader reader = new StreamReader(SDLsList);
            while ((line = reader.ReadLine()) != null)
                sdlFilesDataTable_.Rows.Add(line);
            reader.Close();
            if (chbLoadChecked.Checked)
                updateSdlCheckedListBox() ;
            updateUserInterface() ;
        }
        
        private void btn_save_SDLsList_Click(object sender, EventArgs e) {
             string SDLsList;
        
            SDLsList = @"D:\SDL_File_List.TXT";
            StreamWriter writer = new StreamWriter(SDLsList, false);
            foreach (string fileEntry in sdlCheckedListBox.Items) 
                writer.WriteLine(fileEntry);
            writer.Close();           
        }     
        
        #endregion
        
        void handleSdlListCheckedItem(object sender, ItemCheckEventArgs e)
        {
            updateUserInterface((e.NewValue == CheckState.Checked) ? 1 : -1);
        }
    }
}
